package com.yutel.comp.redis;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisPool {
	private static final Logger log = LoggerFactory.getLogger(RedisPool.class);
	private static ShardedJedisPool shardedJedisPool;
	private static int maxidle = 30000;

	private RedisPool() {
	}

	/**
	 * 获取连接池.
	 * 
	 * @return 连接池实例
	 */
	private static ShardedJedisPool getShardedPool() {
		if (shardedJedisPool == null) {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxIdle(maxidle);
			config.setTestOnBorrow(false);
			List<JedisShardInfo> shards = RedisConfig.getRedis();
			shardedJedisPool = new ShardedJedisPool(config, shards);
		}
		return shardedJedisPool;
	}

	private static class RedisUtilHolder {
		private static RedisPool instance = new RedisPool();
	}

	public static RedisPool getInstance() {
		return RedisUtilHolder.instance;
	}

	/**
	 * 获取Redis实例.
	 * 
	 * @return Redis工具类实例
	 */
	public ShardedJedis getShardedJedis() {
		ShardedJedis jedis = null;
		try {
			jedis = getShardedPool().getResource();
		} catch (Exception e) {
			log.error("get redis master1 failed!", e);
			if (jedis != null) {
				jedis.close();
			}
		}
		return jedis;
	}

	/**
	 * 销毁redis连接池.
	 * 
	 */
	public void destroyJedis() {
		if (shardedJedisPool != null) {
			shardedJedisPool.destroy();
		}
	}

}
